package com.fjec.activity.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjec.activity.entity.BizActivitySeckillCondition;
import com.fjec.activity.entity.BizActivitySeckillUser;
import com.fjec.activity.feign.MarketClient;
import com.fjec.activity.rabbitmq.provider.SecKillProvider;
import com.fjec.activity.view.SecKillShopVO;
import com.fjec.activity.view.UserGiftVO;
import com.fjec.common.annotation.Json;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.JsonUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.apache.shiro.SecurityUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.fjec.activity.service.IBizActivitySeckillService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 004.发布秒杀活动表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2020-09-18
 */
@RestController
@RequestMapping("/")
public class BizActivitySeckillController {

    @Resource
    private IBizActivitySeckillService service;

    @Resource
    private SecKillProvider secKillProvider;

    @Resource
    private MarketClient marketClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/y/seckill/save")
    public JsonResult saveSecKill(@Json List<UserGiftVO> userGiftVOList, Integer markCodes, String partInRoles, int startTime) {
        int code = service.saveSecKill(userGiftVOList, markCodes, partInRoles, startTime);
        if (code == 0)
            return JsonResult.SUCCESS;
        else
            return JsonResult.failure().code("4004").message("礼物数量不足").build();
    }

    @GetMapping("/y/seckill/getSecKillForMe")
    public JsonResult getSecKillForMe(Page page) {
        Map<String, Object> result = service.getSecKillForMe(page);
        return JsonResult.success().data(result).total(MapUtils.getLong(result, "total")).build();
    }

    @GetMapping("/y/seckill/getGivingForMe")
    public JsonResult getGivingForMe(Page page) {
        Map<String, Object> result = service.getGivingForMe(page);
        return JsonResult.success().data(result).total(MapUtils.getLong(result, "total")).build();
    }

    @PostMapping("/y/seckill/doKill")
    public JsonResult doKill(Long secKillOrGivingId, Long busiId, Integer busiType) {
        if (!SecurityUtils.getSubject().isAuthenticated())
            return JsonResult.FAILURE;
        Long userId = AccountInfo.getUserId();
        // redis记录参加过该秒杀的userId
        List<Long> partInUsers = (List<Long>) redisTemplate.opsForValue().get("fjec:seckill:partInUsers:" + secKillOrGivingId);
        if (partInUsers == null)
            partInUsers = new ArrayList<>();
        if (partInUsers.contains(String.valueOf(userId)))
            return JsonResult.failure()
                    .code(EnumSysCode.MSG_6008.getCode())
                    .message(EnumSysCode.MSG_6008.getMsg())
                    .build();
        partInUsers.add(userId);
        redisTemplate.opsForValue().set("fjec:seckill:partInUsers:" + secKillOrGivingId, partInUsers);

        String shopName = AccountInfo.getShopName();
        if (shopName == null)
            shopName = "";
        secKillProvider.sendSecKill(userId, secKillOrGivingId, shopName);
        marketClient.seckillAutoFollow(userId, busiId, busiType);
        return JsonResult.SUCCESS;
    }

    /**
     * 查询我发起的秒杀活动
     * @return
     */
    @GetMapping("/y/seckill/getMySeckillRecords")
    public JsonResult getMySeckillRecords() {
        Long busiId = AccountInfo.getBusiId();
        List<Map<String, Object>> result = service.getMySeckillRecords(busiId);
        return JsonResult.success().data(result).build();
    }

    /**
     * 查询秒杀活动参与用户
     * @param seckillId
     * @return
     */
    @GetMapping("/y/seckill/getSeckillUsersDetail")
    public JsonResult getSeckillUsersDetail(Long seckillId, Page page) {
        List<Map<String, Object>> result = service.getSeckillUsersDetail(seckillId, page);

        return JsonResult
                .success()
                .data(result)
                .total(page.getTotal())
                .build();
    }

    /**
     * 查询用户是否有秒杀或赠与礼物
     * 0=无 1=有秒杀 2=有赠送 3=both
     * @return
     */
    @GetMapping("/seckill/hasSeckillOrGiving")
    public Integer hasSeckillOrGiving(Long userId, Integer busiType, Long busiId) {
        Integer result = service.hasSeckillOrGiving(userId, busiType, busiId);
        return result;
    }
}
